package thread.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现两个线程交替执行
 *
 * @author liweimin
 * @date 2021/5/10 9:51
 * @since
 */
public class Test02 {

    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();
    private boolean flag = false;

    public void printOne() {
        try {
            lock.lock();
            while (flag) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "=====================");
            flag = true;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printTwo() {
        try {
            lock.lock();
            while (!flag) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "*********************");
            flag = false;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Test02 test02 = new Test02();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                test02.printOne();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                test02.printTwo();
            }
        }).start();
    }
}
